import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { IUsr, Usr, UsrDocument } from 'src/module/usr/schemas/usr.schema';
import { UsrService } from 'src/module/usr/usr.service';
import { encryptPassword } from 'src/common/utils/cryptogram';

@Injectable()
export class AuthService {
    constructor(
        private readonly usrService: UsrService,
        private readonly jwtService: JwtService,
    ) { }

    /**
     * 验证用户
     * @param wepoId id
     * @param password 密码
     * @returns 
     */
    async validate(wepoId: string, password: string): Promise<IUsr> {
        const user = await this.usrService.findByWePoId(wepoId);
        if (user) {
            let enPwd = encryptPassword(password, wepoId);
            if (user.pwd == enPwd) {
                return user
            }
        }
        return null
    }

    async login(user: IUsr): Promise<any> {
        const { wepoId, un } = user;
        return {
            token: this.jwtService.sign({ username: un, sub: wepoId })    
        }
    }
}
